import React, { useRef, useEffect, useMemo } from 'react';
import { useSelector } from 'react-redux';

type TUsePermission = (
    roles: string[] | string,
    element: (() => React.ReactElement) | React.ReactElement,
    type?: 'display' | 'disable'
) => React.ReactElement | null;

/**
 * @description 元素级别的权限控制
 * @param {string[] | string} roles 可访问的角色权限数组
 * @param {() => React.ReactElement | React.ReactElement} element 渲染元素的回调函数
 * @param {'display' | 'disable'} type 对于按钮是否采用禁止点击/不显示
 * @return React.ReactElement | null
 */
const usePermission: TUsePermission = (roles = [], element, type = 'display') => {
    const containerRef = useRef(null);
    const { roles: userRole } = useSelector((store) => (store as IStore)?.user);
    const isPermission = useMemo(() => {
        const _roles = Array.isArray(roles) ? roles : [roles];
        return userRole.some((role: string) => _roles.includes(role));
    }, [roles, userRole]);

    // 操作dom，进行控制
    const unDisable = () => {
        const child = (containerRef.current as any)?.children[0];

        // 禁止点击
        if (!isPermission && child) {
            child.disabled = true;
            child.style.cursor = 'not-allowed';
        }
    };

    useEffect(() => {
        unDisable();
    }, [isPermission]);

    const render = React.isValidElement(element)
        ? () => element
        : (element as () => React.ReactElement);

    if (isPermission) return render();
    if (type === 'display') return null;

    const renderElement = React.cloneElement(render(), {
        disabled: true,
    });

    return (
        <div
            style={{ display: 'inline-block' }}
            ref={containerRef}
        >
            {renderElement}
        </div>
    );
};

export default usePermission;
